package com.unibeta.cloudtest.mesher.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.unibeta.cloudtest.mesher.modules.schedule.entity.Job;
import com.unibeta.cloudtest.mesher.modules.schedule.entity.JobRunHistory;
import com.unibeta.cloudtest.mesher.modules.schedule.repo.JobRepo;
import com.unibeta.cloudtest.mesher.modules.schedule.repo.JobRunHistoryRepo;
import com.unibeta.cloudtest.mesher.modules.schedule.service.impl.ScheduleJobTask;
import com.unibeta.cloudtest.mesher.service.ScheduleService;
import com.unibeta.cloudtest.tool.Tools;

import cn.hutool.cron.CronUtil;

@Service
public class ScheduleServiceImpl implements ScheduleService {

	@Autowired
	JobRepo jobRepo;
	@Autowired
	JobRunHistoryRepo jobRunHistoryRepo;

	@Override
	public List<Job> getJobsByUserId(Long userId) throws Exception {
		return jobRepo.getJobsByUserId(userId);
	}

	@Override
	public Job createJob(Job job) throws Exception {

		Job save = jobRepo.save(job);

		return save;
	}

	@Override
	public void removeJob(Long jobId) throws Exception {
		this.stopJob(jobId);
		jobRepo.deleteById(jobId);
	}

	@Override
	public Job updateJob(Job job) throws Exception {
		Job save = jobRepo.save(job);
		return save;
	}

	@Override
	public Boolean startJob(Long jobId) throws Exception {

		if (!CronUtil.getScheduler().isStarted()) {
			CronUtil.getScheduler().start();
		}

		Job job = this.getJob(jobId);
		CronUtil.schedule(job.getId().toString(), job.getCron(), new ScheduleJobTask(job));
		
		return true;
	}

	@Override
	public Boolean stopJob(Long jobId) throws Exception {
		
		CronUtil.remove(jobId.toString());
		
		return true;
	}

	@Override
	public Job getJob(Long jobId) throws Exception {
		return jobRepo.getOne(jobId);
	}

	@Override
	public JobRunHistory saveJobRunHistory(JobRunHistory jobRunHistory) throws Exception {
		return jobRunHistoryRepo.save(jobRunHistory);
	}

	@Override
	public List<JobRunHistory> getJobRunHistoryList(Long jobId) throws Exception {
		return jobRunHistoryRepo.findAllByJobId(jobId);
	}

}
